<!DOCTYPE html>
<html lang="zh-Hans">
<head>

    <!--[if lt IE 9]>
        <style>body {display: none; background: none !important} </style>
        <meta http-equiv="Refresh" Content="0; url=//outdatedbrowser.com/" />
    <![endif]-->

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<meta name="format-detection" content="telephone=no" />
<meta name="author" content="王诗翔" />



<meta name="description" content="内容  使用多个命令 创建脚本文件 显示消息 使用变量 输入输出重定向 管道 数学运算 退出脚本   使用多个命令如果多个命令一起使用，可以放在一行并用分号分隔。 123wsx@wsx-ubuntu:~$ date; who2017年 07月 26日 星期三 09:53:43 CSTwsx      tty7         2017-07-26 09:48 (:0) 创建脚本文件在创建脚本文">
<meta name="keywords" content="bash shell,shell笔记">
<meta property="og:type" content="article">
<meta property="og:title" content="构建基本shell脚本">
<meta property="og:url" content="https://shixiangwang.github.io/2017/08/11/basic-shell/index.html">
<meta property="og:site_name" content="Cloudberry">
<meta property="og:description" content="内容  使用多个命令 创建脚本文件 显示消息 使用变量 输入输出重定向 管道 数学运算 退出脚本   使用多个命令如果多个命令一起使用，可以放在一行并用分号分隔。 123wsx@wsx-ubuntu:~$ date; who2017年 07月 26日 星期三 09:53:43 CSTwsx      tty7         2017-07-26 09:48 (:0) 创建脚本文件在创建脚本文">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-01-27T04:07:39.126Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="构建基本shell脚本">
<meta name="twitter:description" content="内容  使用多个命令 创建脚本文件 显示消息 使用变量 输入输出重定向 管道 数学运算 退出脚本   使用多个命令如果多个命令一起使用，可以放在一行并用分号分隔。 123wsx@wsx-ubuntu:~$ date; who2017年 07月 26日 星期三 09:53:43 CSTwsx      tty7         2017-07-26 09:48 (:0) 创建脚本文件在创建脚本文">

<link rel="apple-touch-icon" href= "/apple-touch-icon.png">


    <link rel="alternate" href="/atom.xml" title="Cloudberry" type="application/atom+xml">



    <link rel="shortcut icon" href="/favicon.png">



    <link href="//cdn.bootcss.com/animate.css/3.5.1/animate.min.css" rel="stylesheet">



    <link href="//cdn.bootcss.com/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet">



    <script src="//cdn.bootcss.com/pace/1.0.2/pace.min.js"></script>
    <link href="//cdn.bootcss.com/pace/1.0.2/themes/blue/pace-theme-minimal.css" rel="stylesheet">


<link rel="stylesheet" href="../../../../css/style.css">



<link href="//cdn.bootcss.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet">


<title>构建基本shell脚本 | Cloudberry</title>

<script src="//cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>
<script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>

<script>
    var yiliaConfig = {
        fancybox: true,
        animate: true,
        isHome: false,
        isPost: true,
        isArchive: false,
        isTag: false,
        isCategory: false,
        fancybox_js: "//cdn.bootcss.com/fancybox/2.1.5/jquery.fancybox.min.js",
        scrollreveal: "//cdn.bootcss.com/scrollReveal.js/3.1.4/scrollreveal.min.js",
        search: true
    }
</script>


    <script>
        yiliaConfig.jquery_ui = [true, "//cdn.bootcss.com/jqueryui/1.10.4/jquery-ui.min.js", "//cdn.bootcss.com/jqueryui/1.10.4/css/jquery-ui.min.css"];
    </script>



    <script> yiliaConfig.rootUrl = "\/";</script>






</head>
<body>
  <div id="container">
    <div class="left-col">
    <div class="overlay"></div>
<div class="intrude-less">
    <header id="header" class="inner">
        <a href="/" class="profilepic">
            <img src="/img/avatar.png" class="animated zoomIn">
        </a>
        <hgroup>
          <h1 class="header-author"><a href="/">王诗翔</a></h1>
        </hgroup>

        
        <p class="header-subtitle">A site for writing life</p>
        

        
            <form id="search-form">
            <input type="text" id="local-search-input" name="q" placeholder="search..." class="search form-control" autocomplete="off" autocorrect="off" searchonload="false" />
            <i class="fa fa-times" onclick="resetSearch()"></i>
            </form>
            <div id="local-search-result"></div>
            <p class='no-result'>No results found <i class='fa fa-spinner fa-pulse'></i></p>
        


        
            <div id="switch-btn" class="switch-btn">
                <div class="icon">
                    <div class="icon-ctn">
                        <div class="icon-wrap icon-house" data-idx="0">
                            <div class="birdhouse"></div>
                            <div class="birdhouse_holes"></div>
                        </div>
                        <div class="icon-wrap icon-ribbon hide" data-idx="1">
                            <div class="ribbon"></div>
                        </div>
                        
                        <div class="icon-wrap icon-link hide" data-idx="2">
                            <div class="loopback_l"></div>
                            <div class="loopback_r"></div>
                        </div>
                        
                        
                        <div class="icon-wrap icon-me hide" data-idx="3">
                            <div class="user"></div>
                            <div class="shoulder"></div>
                        </div>
                        
                    </div>
                    
                </div>
                <div class="tips-box hide">
                    <div class="tips-arrow"></div>
                    <ul class="tips-inner">
                        <li>菜单</li>
                        <li>标签</li>
                        
                        <li>友情链接</li>
                        
                        
                        <li>关于我</li>
                        
                    </ul>
                </div>
            </div>
        

        <div id="switch-area" class="switch-area">
            <div class="switch-wrap">
                <section class="switch-part switch-part1">
                    <nav class="header-menu">
                        <ul>
                        
                            <li><a href="../../../../index.html">主页</a></li>
                        
                            <li><a href="../../../../archives/">所有文章</a></li>
                        
                            <li><a href="../../../../tags/">标签云</a></li>
                        
                            <li><a href="../../../../about/">关于我</a></li>
                        
                        </ul>
                    </nav>
                    <nav class="header-nav">
                        <ul class="social">
                            
                                <a class="fa Email" href="mailto:w_shixiang@163.com" title="Email"></a>
                            
                                <a class="fa GitHub" href="https://github.com/ShixiangWang" title="GitHub"></a>
                            
                                <a class="fa RSS" href="../../../../atom.xml" title="RSS"></a>
                            
                                <a class="fa 知乎" href="https://www.zhihu.com/people/wang-shi-xiang-65/activities" title="知乎"></a>
                            
                                <a class="fa 简书" href="https://www.jianshu.com/u/b6608e27dc74" title="简书"></a>
                            
                                <a class="fa Twitter" href="https://twitter.com/WangShxiang" title="Twitter"></a>
                            
                        </ul>
                    </nav>
                </section>
                
                
                <section class="switch-part switch-part2">
                    <div class="widget tagcloud" id="js-tagcloud">
                        <ul class="tag-list"><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/Gist/">Gist</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/Linux-shell/">Linux shell</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/OOP/">OOP</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/R/">R</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/Rmarkdown/">Rmarkdown</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/Rmd/">Rmd</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/Rstudio/">Rstudio</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/bash-shell/">bash shell</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/fasta/">fasta</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/git/">git</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/github/">github</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/lapply/">lapply</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/linux/">linux</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/markdown/">markdown</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/md/">md</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/python/">python</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/sapply/">sapply</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/sed/">sed</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/shell笔记/">shell笔记</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/survival/">survival</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/survminer/">survminer</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/vapply/">vapply</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/写作/">写作</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/数据处理/">数据处理</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/文本处理/">文本处理</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/生存分析/">生存分析</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/生物信息学/">生物信息学</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/类/">类</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/迭代计算/">迭代计算</a></li></ul>
                    </div>
                </section>
                
                
                
                <section class="switch-part switch-part3">
                    <div id="js-friends">
                    
                      <a class="main-nav-link switch-friends-link" href="http://www.ruanyifeng.com/blog/archives.html">阮一峰的网络日志</a>
                    
                      <a class="main-nav-link switch-friends-link" href="http://blog.fens.me/series-r/">R的极客理想系列</a>
                    
                      <a class="main-nav-link switch-friends-link" href="https://yihui.name/">谢益辉</a>
                    
                      <a class="main-nav-link switch-friends-link" href="http://www.huangshujia.me/">解螺旋的矿工</a>
                    
                      <a class="main-nav-link switch-friends-link" href="https://github.com/GuangchuangYu">GuangchuangYu</a>
                    
                      <a class="main-nav-link switch-friends-link" href="https://vip.biotrainee.com/">生信技能树</a>
                    
                    </div>
                </section>
                

                
                
                <section class="switch-part switch-part4">
                
                    <div id="js-aboutme">人该是自己生活的主宰，而不是别人手中的行货</div>
                </section>
                
            </div>
        </div>
    </header>                
</div>
    </div>
    <div class="mid-col">
      <nav id="mobile-nav">
      <div class="overlay">
          <div class="slider-trigger"></div>
          <h1 class="header-author js-mobile-header hide"><a href="/" title="回到主页">王诗翔</a></h1>
      </div>
    <div class="intrude-less">
        <header id="header" class="inner">
            <a href="/" class="profilepic">
                <img src="/img/avatar.png" class="animated zoomIn">
            </a>
            <hgroup>
              <h1 class="header-author"><a href="/" title="回到主页">王诗翔</a></h1>
            </hgroup>
            
            <p class="header-subtitle">A site for writing life</p>
            
            <nav class="header-menu">
                <ul>
                
                    <li><a href="../../../../index.html">主页</a></li>
                
                    <li><a href="../../../../archives/">所有文章</a></li>
                
                    <li><a href="../../../../tags/">标签云</a></li>
                
                    <li><a href="../../../../about/">关于我</a></li>
                
                <div class="clearfix"></div>
                </ul>
            </nav>
            <nav class="header-nav">
                        <ul class="social">
                            
                                <a class="fa Email" target="_blank" href="mailto:w_shixiang@163.com" title="Email"></a>
                            
                                <a class="fa GitHub" target="_blank" href="https://github.com/ShixiangWang" title="GitHub"></a>
                            
                                <a class="fa RSS" target="_blank" href="../../../../atom.xml" title="RSS"></a>
                            
                                <a class="fa 知乎" target="_blank" href="https://www.zhihu.com/people/wang-shi-xiang-65/activities" title="知乎"></a>
                            
                                <a class="fa 简书" target="_blank" href="https://www.jianshu.com/u/b6608e27dc74" title="简书"></a>
                            
                                <a class="fa Twitter" target="_blank" href="https://twitter.com/WangShxiang" title="Twitter"></a>
                            
                        </ul>
            </nav>
        </header>                
    </div>
    <link class="menu-list" tags="标签" friends="友情链接" about="关于我"/>
</nav>
      <div class="body-wrap"><article id="post-basic-shell" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a href="" class="article-date">
      <time datetime="2017-08-10T16:00:00.000Z" itemprop="datePublished">2017-08-11</time>
</a>


    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      构建基本shell脚本
    </h1>
  

      </header>
      
      <div class="article-info article-info-post">
        
    <div class="article-category tagcloud">
    <a class="article-category-link" href="../../../../categories/Linux杂烩/">Linux杂烩</a><a class="article-category-link" href="../../../../categories/Linux杂烩/shell编程/">shell编程</a>
    </div>


        
    <div class="article-tag tagcloud">
        <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="../../../../tags/bash-shell/">bash shell</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="../../../../tags/shell笔记/">shell笔记</a></li></ul>
    </div>

        <div class="clearfix"></div>
      </div>
      
    
    <div class="article-entry" itemprop="articleBody">
      
          
        <a id="more"></a>
<blockquote>
<p><strong>内容</strong></p>
<ul>
<li>使用多个命令</li>
<li>创建脚本文件</li>
<li>显示消息</li>
<li>使用变量</li>
<li>输入输出重定向</li>
<li>管道</li>
<li>数学运算</li>
<li>退出脚本</li>
</ul>
</blockquote>
<h3 id="使用多个命令"><a href="#使用多个命令" class="headerlink" title="使用多个命令"></a>使用多个命令</h3><p>如果多个命令一起使用，可以放在一行并用分号分隔。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~$ date; who</span><br><span class="line">2017年 07月 26日 星期三 09:53:43 CST</span><br><span class="line">wsx      tty7         2017-07-26 09:48 (:0)</span><br></pre></td></tr></table></figure>
<h3 id="创建脚本文件"><a href="#创建脚本文件" class="headerlink" title="创建脚本文件"></a>创建脚本文件</h3><p>在创建脚本文件时，必须在文件的第一行指定要使用的shell，格式为：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#!/bin/bash</span></span><br></pre></td></tr></table></figure>
<p>脚本文件的第一行中<code>#</code>后的惊叹号会告诉shell使用哪个shell来运行脚本（如果是其他编码语言脚本，像python，第一行类似）。</p>
<p>其他地方的<code>#</code>用作注释行。</p>
<p>添加名为<code>test1</code>的脚本文件，内容为：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#!/bin/bash</span></span><br><span class="line"><span class="comment"># This script displays the date and who's logged on</span></span><br><span class="line">date</span><br><span class="line">who</span><br></pre></td></tr></table></figure>
<p>现在运行脚本，结果会是：</p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">wsx<span class="meta">@wsx</span>-<span class="string">ubuntu:</span>~/script_learn$ test1</span><br><span class="line">未找到 <span class="string">'test1'</span> 命令，您要输入的是否是：</span><br><span class="line"> 命令 <span class="string">'testr'</span> 来自于包 <span class="string">'python3-testrepository'</span> (main)</span><br><span class="line"> 命令 <span class="string">'testr'</span> 来自于包 <span class="string">'python-testrepository'</span> (universe)</span><br><span class="line"> 命令 <span class="string">'test'</span> 来自于包 <span class="string">'coreutils'</span> (main)</span><br><span class="line">test1：未找到命令</span><br></pre></td></tr></table></figure>
<p>我们现在需要做的是让bash shell能够找到我们的脚本文件。shell会通过<code>PATH</code>环境变量来查找命令，我们可以看看：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ echo $PATH</span><br><span class="line">/home/wsx/Anaconda/bin:/home/wsx/Anoconda/ENTER/bin:/usr/lib/jvm/default-java/bin:/home/wsx/bin:/home/wsx/Anaconda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin</span><br></pre></td></tr></table></figure>
<p>很显然，我们的文件没有在这些目录范围内。要让shell找到test1脚本，我们可以采取以下两种做法之一：</p>
<ul>
<li>将shell脚本文件所处的目录添加到<code>PATH</code>环境变量中；</li>
<li>在提示符中用绝对路径或相对路径来引用shell脚本文件。</li>
</ul>
<p>第二种方法比较简单，我们在这里试试：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ ./test1</span><br><span class="line">bash: ./test1: 权限不够</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ ll test1 # 发现权限不够，查看文件的权限</span><br><span class="line">-rw-rw-r-- 1 wsx wsx 73 7月  26 10:03 test1</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ chmod u+x test1 # 修改权限，添加可执行属性</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ ./test1 # 成功运行脚本</span><br><span class="line">2017年 07月 26日 星期三 10:09:23 CST</span><br><span class="line">wsx      tty7         2017-07-26 09:48 (:0)</span><br></pre></td></tr></table></figure>
<h3 id="显示消息"><a href="#显示消息" class="headerlink" title="显示消息"></a>显示消息</h3><p>在<code>echo</code>命令后面加上一个字符串，就能显示出这个文本字符串。这种方式可以添加自己的文本消息来告诉脚本用户脚本正在做什么。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ echo This is a test</span><br><span class="line">This is a test</span><br></pre></td></tr></table></figure>
<p>如果文本本身带有字符串，我们需要<strong>用单引号或双引号来划定文本字符串</strong>。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ echo "Let's see if this'll work"</span><br><span class="line">Let's see if this'll work</span><br></pre></td></tr></table></figure>
<p>我们修改下之前的test1文件，增加消息显示：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> This script displays the date and who<span class="string">'s logged on</span></span></span><br><span class="line">echo The time and date are:</span><br><span class="line">date</span><br><span class="line">echo "Let's see who's logged into the system"</span><br><span class="line">who</span><br></pre></td></tr></table></figure>
<p>运行：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ ./test1</span><br><span class="line">The time and date are:</span><br><span class="line">2017年 07月 26日 星期三 10:17:59 CST</span><br><span class="line">Let's see who's logged into the system</span><br><span class="line">wsx      tty7         2017-07-26 09:48 (:0)</span><br></pre></td></tr></table></figure>
<p><strong>如果想把文本字符串和命令输出显示在同一行中</strong>，可以用<code>echo</code>语句的<code>-n</code>参数。需要在字符串的两侧加上引号，并且保证字符串尾部有一个空格（不然字符串和命令输出就粘连到一起了）。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> This script displays the date and who<span class="string">'s logged on</span></span></span><br><span class="line">echo -n "The time and date are: "</span><br><span class="line">date</span><br><span class="line">echo  "Let's see who's logged into the system: "</span><br><span class="line">who</span><br><span class="line"></span><br><span class="line"><span class="meta">#</span><span class="bash"> 运行结果输出</span></span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ ./test1</span><br><span class="line">The time and date are: 2017年 07月 26日 星期三 10:24:04 CST</span><br><span class="line">Let's see who's logged into the system:</span><br><span class="line">wsx      tty7         2017-07-26 09:48 (:0)</span><br></pre></td></tr></table></figure>
<h3 id="使用变量"><a href="#使用变量" class="headerlink" title="使用变量"></a>使用变量</h3><p>变量允许我们临时性地将信息存储在shell脚本中，以便和脚本中的其他命令一起使用。</p>
<p><strong>环境变量</strong></p>
<p>shell维护着一组环境变量，用来记录特定的系统信息。比如系统的名称、登录到系统上的用户名、用户的系统ID(也称为UID)、用户默认主目录以及shell查找程序的搜索路径。</p>
<p>使用<code>set</code>命令显示一份完整的当前环境变量列表。<code>env</code>与<code>printenv</code>命令都可以显示全局变量。（这些命令输出结果比较多，不展示了。之前关于环境变量的笔记有比较详细的描述。）</p>
<p>在环境变量名称之前加上美元符可以使用这些环境变量。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ cat test2</span><br><span class="line"><span class="meta">#</span><span class="bash">! /bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> display user information from the system</span></span><br><span class="line">echo "User info for userid: $USER"</span><br><span class="line">echo UID: $UID</span><br><span class="line">echo HOME: $HOME</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ chmod u+x test2</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ ./test2</span><br><span class="line">User info for userid: wsx</span><br><span class="line">UID: 1000</span><br><span class="line">HOME: /home/wsx</span><br></pre></td></tr></table></figure>
<p>可以想象的到，如果我们想要使用实际的美元符而不是引用变量，肯定会出问题。这时候我们需要在美元符前面加上<code>\</code>进行转义，以显示美元符本身。</p>
<p><strong>用户变量</strong></p>
<p>使用等号将值赋给用户变量。<strong>注意，在变量、等号和值之间不能出现空格！</strong>这个是初学者常见的一个问题，本人也非常不太适应这个。因为在其他语言中不区分等号两边的空格，相信接触过其他脚本的朋友们肯定有习惯打空格使代码美观的，这在bash shell中是万万行不通滴。</p>
<p>一个使用的例子：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ cat test3</span><br><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> testing variables</span></span><br><span class="line">days=10</span><br><span class="line">guest="Katie"</span><br><span class="line">echo "$guest checked in $days days ago"</span><br><span class="line">days=5</span><br><span class="line">guest="Jessica"</span><br><span class="line">echo "$guest checked in $days days ago"</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ chmod u+x test3</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ ./test3</span><br><span class="line">Katie checked in 10 days ago</span><br><span class="line">Jessica checked in 5 days ago</span><br></pre></td></tr></table></figure>
<p>变量每次被引用时，都会输出当前赋给它的值。重要的是要记住，引用一个变量值时需要使用美元符，而引用变量来对其进行赋值时则不需要使用美元符。</p>
<h3 id="命令替换"><a href="#命令替换" class="headerlink" title="命令替换"></a>命令替换</h3><p>shell脚本最有用的特性之一就是可以从命令输出中提取信息，并将其赋给变量。</p>
<p>有两种方法可以将命令输出赋给变量：</p>
<ul>
<li>反引号字符(`)</li>
<li>$()格式</li>
</ul>
<figure class="highlight makefile"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">要么用一对反引号把整个命令行命令围起来：</span><br><span class="line">testing=`date`</span><br><span class="line">要么使用$()格式</span><br><span class="line">testing=<span class="variable">$(date)</span></span><br></pre></td></tr></table></figure>
<p>下面是一个例子，在脚本中通过命令替换获得当前日期并用它来生成唯一文件名：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ cat test4</span><br><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> copy the /usr/bin directory listing to a <span class="built_in">log</span> file</span></span><br><span class="line">today=$(date +%y%m%d)</span><br><span class="line">ls /usr/bin -al &gt; log.$today</span><br><span class="line"></span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ chmod u+x test4</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ ./test4</span><br></pre></td></tr></table></figure>
<h3 id="重定向输入和输出"><a href="#重定向输入和输出" class="headerlink" title="重定向输入和输出"></a>重定向输入和输出</h3><p>通过几个操作符进行重定向，我们可以将命令的结果输出到另外的位置（文件）。当然，重定向可以用于输入。</p>
<p><strong>输出重定向</strong></p>
<p>最基本的操作符是<code>&gt;</code>。比如我们想要输出命令结果到一个指定文件：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ date &gt; test6</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ ls -l test6</span><br><span class="line">-rw-rw-r-- 1 wsx wsx 43 7月  26 16:42 test6</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ cat test6</span><br><span class="line">2017年 07月 26日 星期三 16:42:34 CST</span><br></pre></td></tr></table></figure>
<p>如果想要将命令的输出追加到已有文件中，需要用双大于号（&gt;&gt;）来追加数据。</p>
<p><strong>输入重定向</strong></p>
<p>输入重定向和输出重定向正好相反。输入重定向将文件的内容重定向到命令，而非将命令的输出重定向到文件。</p>
<p>使用的符号是小于号（&lt;）。</p>
<blockquote>
<p>一种简单的记忆方法是：在命令行上，命令总是在左侧，而重定向符号“指向”数据流动的方向。小于号说明数据正在从输入文件流向命令。</p>
</blockquote>
<p>比如用wc命令检查文本的行数、词数和字节数。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ wc &lt; test6</span><br><span class="line"> 1  6 43</span><br></pre></td></tr></table></figure>
<p>另一种输入重定向的方法是<strong>内联输入重定向</strong>。它无需使用文件进行重定向，只需要在命令行中指定用于输入重定向的数据即可。它使用的符号是远小于号（&lt;&lt;），除了这个符号，我们还需要指定一个文本标记用来划分输入数据的开始和结尾。任何字符串都可以作为文本标记，但在数据的开始和结尾文本标记必须一致。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ wc &lt;&lt; EOF</span><br><span class="line"><span class="meta">&gt;</span><span class="bash"> <span class="built_in">test</span> string1</span></span><br><span class="line"><span class="meta">&gt;</span><span class="bash"> <span class="built_in">test</span> string2</span></span><br><span class="line"><span class="meta">&gt;</span><span class="bash"> <span class="built_in">test</span> string3</span></span><br><span class="line"><span class="meta">&gt;</span><span class="bash"> EOF</span></span><br><span class="line"> 3  6 39</span><br></pre></td></tr></table></figure>
<p>它的形式为：</p>
<figure class="highlight haskell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="title">command</span> &lt;&lt; marker</span><br><span class="line"><span class="class"><span class="keyword">data</span></span></span><br><span class="line"><span class="title">marker</span></span><br></pre></td></tr></table></figure>
<h3 id="管道"><a href="#管道" class="headerlink" title="管道"></a>管道</h3><p>有时候需要将一个命令的输出作为另一个命令的输入。通过<code>|</code>符号分隔命令即可实现管道。</p>
<p>比如我想查看某个文件（test1）的前两行并进行排序，操作如下：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ cat test1</span><br><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> This script displays the date and who<span class="string">'s logged on</span></span></span><br><span class="line">echo -n "The time and date are: "</span><br><span class="line">date</span><br><span class="line">echo  "Let's see who's logged into the system: "</span><br><span class="line">who</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ cat test1 | head -2 | sort</span><br><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> This script displays the date and who<span class="string">'s logged on</span></span></span><br></pre></td></tr></table></figure>
<p>管道的强大之处在于可以根据自己的需求灵活地组合和使用各种linux命令工具。这里只是一个简单的例子，要熟练掌握少不了平时多多研究和练习。</p>
<h3 id="执行数学运算"><a href="#执行数学运算" class="headerlink" title="执行数学运算"></a>执行数学运算</h3><p>对shell脚本来说，执行数学运算非常麻烦。有两种实现方式。</p>
<p><strong>expr</strong>命令</p>
<p><code>expr</code>命令允许在命令行上处理数学表达式，但是特别笨拙。（Bourne shell中）</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ exrpr 1 + 5</span><br><span class="line">未找到 'exrpr' 命令，您要输入的是否是：</span><br><span class="line"> 命令 'expr' 来自于包 'coreutils' (main)</span><br><span class="line">exrpr：未找到命令</span><br></pre></td></tr></table></figure>
<p>看到没有，那算了。它基本涉及的操作跟我们使用的其他语言是一致的。但是有些问题需要处理，像<code>*</code>是通配符，在运算是是做乘号处理的，需要进行转义。</p>
<p><strong>使用方括号</strong></p>
<p>bash shell提供了一种更简单的方法来执行数学表达式。在bash中，在将一个数学运算结果赋给某个变量时，可以用美元符和方括号（$[operator]）将数学表达式围起来。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ var1=$[1+5]</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ echo $var1</span><br><span class="line">6</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ var2=$[$var1+2]</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ echo $var2</span><br><span class="line">8</span><br></pre></td></tr></table></figure>
<p>这种方式不仅方便，而且因为在方括号内，不会让shell误解乘号或其他符号。</p>
<p>但bash shell计算有一个主要限制：<strong>它只支持整数运算！</strong></p>
<p><strong>浮点解决方案</strong></p>
<p>最常见的方案是用内建的bash计算器。它实际上是一门编程语言，它允许在命令行中输入浮点表达式，然后解释并计算该表达式，最后返回结果。bash计算器能够识别：</p>
<ul>
<li>数字（整数和浮点数）</li>
<li>变量（简单变量和数组）</li>
<li>注释（/<em> </em>/开始的行）</li>
<li>表达式</li>
<li>编程语句</li>
<li>函数</li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ bc</span><br><span class="line">bc 1.06.95</span><br><span class="line">Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.</span><br><span class="line">This is free software with ABSOLUTELY NO WARRANTY.</span><br><span class="line">For details type `warranty'.</span><br><span class="line">12 * 5.4</span><br><span class="line">64.8</span><br><span class="line">3.156 * (3 + 5)</span><br><span class="line">25.248</span><br><span class="line">quit</span><br></pre></td></tr></table></figure>
<p>在脚本中使用bc</p>
<p>可以用命令替换运行bc命令，并将输出赋给一个变量。基本格式如下：</p>
<figure class="highlight gams"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">variable</span>=$(echo <span class="comment">"options; expression"</span> |<span class="comment"> bc)</span></span><br></pre></td></tr></table></figure>
<p>options设置变量，expression参数定义了通过bc执行的数学表达式。</p>
<p>看一个简单实例：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ cat test9</span><br><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line">var1=$(echo "scale=4; 3.44/5" | bc)</span><br><span class="line">echo The answer is $var1</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ chmod u+x test9</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ ./test9</span><br><span class="line">The answer is .6880</span><br></pre></td></tr></table></figure>
<p>这个例子将<code>scale</code>变量设置为四位小数，并在<code>expression</code>部分指定了特定的运算。</p>
<p>这个方法适用于较短的运算，但有时我们会涉及更多的数字。如果需要进行大量运算，在一个命令行中列出多个表达式就会有点麻烦。</p>
<p>这里有一个解决方法：使用内联输入重定向，将一个文件重定向到bc命令来处理。格式为：</p>
<figure class="highlight gauss"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">variable=$(bc &lt;&lt; <span class="built_in">EOF</span></span><br><span class="line">options</span><br><span class="line"><span class="built_in">statements</span></span><br><span class="line">expressions</span><br><span class="line"><span class="built_in">EOF</span>)</span><br></pre></td></tr></table></figure>
<p><code>EOF</code>文本字符串标识了内联重定向数据的起始。注意，仍然需要命令替换符号将bc命令的输出赋给变量。</p>
<p>下面是一个例子：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ cat test10</span><br><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"></span><br><span class="line">var1=10.46</span><br><span class="line">var2=43.67</span><br><span class="line">var3=33.2</span><br><span class="line">var4=71</span><br><span class="line"></span><br><span class="line">var5=$(bc &lt;&lt;EOF</span><br><span class="line">scale=4</span><br><span class="line">a1 = ( $var1 * $var2)</span><br><span class="line">b1 = ( $var3 * $var4)</span><br><span class="line">a1 + b1</span><br><span class="line">EOF</span><br><span class="line">)</span><br><span class="line"></span><br><span class="line">echo The final answer for this mess is $var5</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ chmod u+x test10</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ ./test10</span><br><span class="line">The final answer for this mess is 2813.9882</span><br></pre></td></tr></table></figure>
<p>在普通的shell脚本中，数字默认当做字符串处理。这也是为什么我们脚本处理计算麻烦和我们需要特定的工具和方法来进行处理。一定要注意区分。</p>
<h3 id="退出脚本"><a href="#退出脚本" class="headerlink" title="退出脚本"></a>退出脚本</h3><p>前面运行的脚本都是命令执行完成，脚本自动结束。其实我们可以用更为优雅的方式告诉shell命令运行完成，因为每个命令都使用<strong>退出状态码（exit status）</strong>，它是一个0-255的整数值，我们可以捕获这个值并在脚本中使用。</p>
<p>Linux提供了一个专门的变量<code>$?</code>来保存上个已执行命令的退出状态码。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ date</span><br><span class="line">2017年 07月 27日 星期四 10:44:18 CST</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ echo $?</span><br><span class="line">0</span><br></pre></td></tr></table></figure>
<p>按照惯例，一个成功结束的命令的退出状态码是0。如果有错误，则显示一个正数值。</p>
<p>Linux错误退出状态码没有什么标准，但有一些参考：</p>
<table>
<thead>
<tr>
<th>状态码</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>命令成功结束</td>
</tr>
<tr>
<td>1</td>
<td>一般性未知错误</td>
</tr>
<tr>
<td>2</td>
<td>不适合的shell命令</td>
</tr>
<tr>
<td>126</td>
<td>命令不可执行</td>
</tr>
<tr>
<td>127</td>
<td>没找到命令</td>
</tr>
<tr>
<td>128</td>
<td>无效的退出参数</td>
</tr>
<tr>
<td>128+x</td>
<td>与Linux信号x相关的严重错误</td>
</tr>
<tr>
<td>130</td>
<td>通过Ctrl+C终止的命令</td>
</tr>
<tr>
<td>255</td>
<td>正常范围之外的退出状态码</td>
</tr>
</tbody>
</table>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ asfg</span><br><span class="line">未找到 'asfg' 命令，您要输入的是否是：</span><br><span class="line"> 命令 'asdfg' 来自于包 'aoeui' (universe)</span><br><span class="line">asfg：未找到命令</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ echo $?</span><br><span class="line">127</span><br></pre></td></tr></table></figure>
<p><strong>exit命令</strong></p>
<p>默认，shell脚本会以脚本最后的一个命令的退出状态码退出。</p>
<p>但是我们可以改变这种默认行为，返回自己的退出状态码。exit命令允许在脚本结束时指定一个状态退出码。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ cat test13</span><br><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> testing the <span class="built_in">exit</span> status</span></span><br><span class="line">var1=10</span><br><span class="line">var2=30</span><br><span class="line">var3=$[$var1 + $var2]</span><br><span class="line">echo The answer is $var3</span><br><span class="line">exit 5</span><br><span class="line"></span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ chmod u+x test13</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ ./test13</span><br><span class="line">The answer is 40</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ echo $?</span><br><span class="line">5</span><br></pre></td></tr></table></figure>
<p>注意最大255，如果大于它，得到的是求模的结果（余数）。</p>

      
    </div>
    
  </div>
  
    
    <div class="copyright">
        <p><span>本文标题:</span><a href="">构建基本shell脚本</a></p>
        <!-- modify author information
        <p><span>文章作者:</span><a href="/" title="回到主页">王诗翔</a></p>
        -->
        <p><span>文章作者:</span>王诗翔</p>
        <p><span>发布时间:</span>2017-08-11, 00:00:00</p>
        <p><span>最后更新:</span>2018-01-27, 12:07:39</p>
        <p>
            <span>原始链接:</span><a class="post-url" href="" title="构建基本shell脚本">https://shixiangwang.github.io/2017/08/11/basic-shell/</a>
            <span class="copy-path" data-clipboard-text="原文: https://shixiangwang.github.io/2017/08/11/basic-shell/　　作者: 王诗翔" title="点击复制文章链接"><i class="fa fa-clipboard"></i></span>
            <script> var clipboard = new Clipboard('.copy-path'); </script>
        </p>
        <p>
            <span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/" title="CC BY-NC-SA 4.0 International" target = "_blank">"署名-非商用-相同方式共享 4.0"</a> 转载请保留原文链接及作者。
        </p>
    </div>



    <nav id="article-nav">
        
            <div id="article-nav-newer" class="article-nav-title">
                <a href="../structural-command-of-shell/">
                    Linux结构化命令
                </a>
            </div>
        
        
    </nav>


  
</article>

    <div id="toc" class="toc-article">
        <strong class="toc-title">文章目录</strong>
        
            <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#使用多个命令"><span class="toc-number">1.</span> <span class="toc-text">使用多个命令</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#创建脚本文件"><span class="toc-number">2.</span> <span class="toc-text">创建脚本文件</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#显示消息"><span class="toc-number">3.</span> <span class="toc-text">显示消息</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#使用变量"><span class="toc-number">4.</span> <span class="toc-text">使用变量</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#命令替换"><span class="toc-number">5.</span> <span class="toc-text">命令替换</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#重定向输入和输出"><span class="toc-number">6.</span> <span class="toc-text">重定向输入和输出</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#管道"><span class="toc-number">7.</span> <span class="toc-text">管道</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#执行数学运算"><span class="toc-number">8.</span> <span class="toc-text">执行数学运算</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#退出脚本"><span class="toc-number">9.</span> <span class="toc-text">退出脚本</span></a></li></ol>
        
    </div>
    <style>
        .left-col .switch-btn,
        .left-col .switch-area {
            display: none;
        }
        .toc-level-3 i,
        .toc-level-3 ol {
            display: none !important;
        }
    </style>

    <input type="button" id="tocButton" value="隐藏目录"  title="点击按钮隐藏或者显示文章目录">

    <script>
        yiliaConfig.toc = ["隐藏目录", "显示目录", !!"false"];
    </script>



    
<div class="share">
    
        <div class="bdsharebuttonbox">
            <a href="#" class="fa fa-twitter bds_twi" data-cmd="twi" title="分享到推特"></a>
            <a href="#" class="fa fa-weibo bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a>
            <a href="#" class="fa fa-qq bds_sqq" data-cmd="sqq" title="分享给 QQ 好友"></a>
            <a href="#" class="fa fa-files-o bds_copy" data-cmd="copy" title="复制网址"></a>
            <a href="#" class="fa fa fa-envelope-o bds_mail" data-cmd="mail" title="通过邮件分享"></a>
            <a href="#" class="fa fa-weixin bds_weixin" data-cmd="weixin" title="生成文章二维码"></a>
            <a href="#" class="fa fa-share-alt bds_more" data-cmd="more"></i></a>
        </div>
        <script>
            window._bd_share_config={
                "common":{"bdSnsKey":{},"bdText":"构建基本shell脚本　| Cloudberry　","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"24"},"share":{}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];
        </script>
    

    
</div>







    
        <section id="comments">
    <style> aside.comment-bar { margin: auto 30px; }</style>
    <div id="disqus_thread"></div>
    <script>
        var disqus_config = function(){
            this.page.url = 'https://shixiangwang.github.io/2017/08/11/basic-shell/';
            this.page.identifier = '2017/08/11/basic-shell/';
        };
        var loadComment = function(){
            var d = document, s = d.createElement('script');
            s.src = '//Cloudberry.disqus.com/embed.js';
            s.setAttribute('data-timestamp', +new Date());
            (d.head || d.body).appendChild(s);
        }
    </script>
    
    <script> loadComment(); </script>

</section>


    




    <div class="scroll" id="post-nav-button">
        
            <a href="../structural-command-of-shell/" title="上一篇: Linux结构化命令">
                <i class="fa fa-angle-left"></i>
            </a>
        

        <a title="文章列表"><i class="fa fa-bars"></i><i class="fa fa-times"></i></a>

        
            <a href="/" title="回到主页"><i class="fa fa-home"></i></a>
        
    </div>

    <ul class="post-list"><li class="post-list-item"><a class="post-list-link" href="../../../../2018/02/26/python-basics/">两天研习Python基础</a></li><li class="post-list-item"><a class="post-list-link" href="../../../../2018/02/12/how-to-create-an-independent-figpath/">为markdown博文创建独立图片路径</a></li><li class="post-list-item"><a class="post-list-link" href="../../../../2018/02/10/easy-sapply-apply-vapply/">简单理解lapply,sapply,vapply</a></li><li class="post-list-item"><a class="post-list-link" href="../../../../2018/02/07/how-to-do-group-survival-analysis/">怎么对连续变量分组并进行生存分析</a></li><li class="post-list-item"><a class="post-list-link" href="../../../../2018/02/06/how-to-write-rmd-documents-in-hexo-system/">怎么在hexo博客系统中用Rmarkdown写文章</a></li><li class="post-list-item"><a class="post-list-link" href="../../../../2018/01/31/sed-how-to-filter-rows-before-using-command/">sed如何在执行命令前过滤特定文本行</a></li><li class="post-list-item"><a class="post-list-link" href="../../../../2018/01/31/sync-deploy-tools/">Sync deploy 命令工具</a></li><li class="post-list-item"><a class="post-list-link" href="../../../12/25/sed-and-gawk/">初识sed与awk</a></li><li class="post-list-item"><a class="post-list-link" href="../../../12/08/Git-basic-operation/">学习git</a></li><li class="post-list-item"><a class="post-list-link" href="../../../11/29/shell-create-text-menu-and-window/">使用shell创建文本菜单和窗口部件</a></li><li class="post-list-item"><a class="post-list-link" href="../../../11/26/shell-create-function/">创建和使用shell函数</a></li><li class="post-list-item"><a class="post-list-link" href="../../../09/20/OOPinR/">R-面向对象编程</a></li><li class="post-list-item"><a class="post-list-link" href="../../../09/15/Class-in-R/">R中的属性与类</a></li><li class="post-list-item"><a class="post-list-link" href="../../../09/04/control_shell/">控制脚本</a></li><li class="post-list-item"><a class="post-list-link" href="../../../09/03/Linux-data-analysis-tools/">Linux数据处理命令工具</a></li><li class="post-list-item"><a class="post-list-link" href="../../21/shell-show-data/">Linux脚本编程——呈现数据</a></li><li class="post-list-item"><a class="post-list-link" href="../../19/working-with-user-input/">Shell脚本之处理用户输入</a></li><li class="post-list-item"><a class="post-list-link" href="../structural-command-of-shell/">Linux结构化命令</a></li><li class="post-list-item"><a class="post-list-link" href="">构建基本shell脚本</a></li></ul>




    <script>
        
    </script>
</div>
      <footer id="footer">
    <div class="outer">
        <div id="footer-info">
            <div class="footer-left">
                <i class="fa fa-copyright"></i> 
                2017-2018 王诗翔
            </div>
            <div class="footer-right">
                <a href="http://hexo.io/" target="_blank" title="快速、简洁且高效的博客框架">Hexo</a>  Theme <a href="https://github.com/MOxFIVE/hexo-theme-yelee" target="_blank" title="简而不减 Hexo 双栏博客主题  v3.5">Yelee</a> by MOxFIVE <i class="fa fa-heart animated infinite pulse"></i>
            </div>
        </div>
        
            <div class="visit">
                
                    <span id="busuanzi_container_site_pv" style='display:none'>
                        <span id="site-visit" title="本站到访数"><i class="fa fa-user" aria-hidden="true"></i><span id="busuanzi_value_site_uv"></span>
                        </span>
                    </span>
                
                
                    <span>| </span>
                
                
                    <span id="busuanzi_container_page_pv" style='display:none'>
                        <span id="page-visit"  title="本页阅读量"><i class="fa fa-eye animated infinite pulse" aria-hidden="true"></i><span id="busuanzi_value_page_pv"></span>
                        </span>
                    </span>
                
            </div>
        
    </div>
</footer>
    </div>
    
    <script src="../../../../js/GithubRepoWidget.js"></script>

<script data-main="/js/main.js" src="//cdn.bootcss.com/require.js/2.2.0/require.min.js"></script>

    <script>
        $(document).ready(function() {
            var iPad = window.navigator.userAgent.indexOf('iPad');
            if (iPad > -1 || $(".left-col").css("display") === "none") {
                var bgColorList = ["#9db3f4", "#414141", "#e5a859", "#f5dfc6", "#c084a0", "#847e72", "#cd8390", "#996731"];
                var bgColor = Math.ceil(Math.random() * (bgColorList.length - 1));
                $("body").css({"background-color": bgColorList[bgColor], "background-size": "cover"});
            }
            else {
                var backgroundnum = 2;
                var backgroundimg = "url(/background/bg-x.jpg)".replace(/x/gi, Math.ceil(Math.random() * backgroundnum));
                $("body").css({"background": backgroundimg, "background-attachment": "fixed", "background-size": "cover"});
            }
        })
    </script>





    <script type="text/x-mathjax-config">
MathJax.Hub.Config({
    tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
        processEscapes: true,
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    }
});

MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for(i=0; i < all.length; i += 1) {
        all[i].SourceElement().parentNode.className += ' has-jax';                 
    }       
});
</script>

<script src="//cdn.bootcss.com/mathjax/2.6.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>


<div class="scroll" id="scroll">
    <a href="#" title="返回顶部"><i class="fa fa-arrow-up"></i></a>
    <a href="#comments" onclick="load$hide();" title="查看评论"><i class="fa fa-comments-o"></i></a>
    <a href="#footer" title="转到底部"><i class="fa fa-arrow-down"></i></a>
</div>
<script>
    // Open in New Window
    
        var oOpenInNew = {
             github: ".github-widget a", 
            
             post: ".article-entry a[href], .copyright a[href]", 
            
            
            
             archives: ".archive-article-title", 
             miniArchives: "a.post-list-link", 
            
             friends: "#js-friends a", 
             socail: ".social a" 
        }
        for (var x in oOpenInNew) {
            $(oOpenInNew[x]).attr("target", "_blank");
        }
    
</script>

    <script>
        var originTitle = document.title;
        var titleTime;
        document.addEventListener("visibilitychange", function() {
            if (document.hidden) {
                document.title = "(つェ⊂) 我藏好了哦~ " + originTitle;
                clearTimeout(titleTime);
            }
            else {
                document.title = "(*´∇｀*) 被你发现啦~ " + originTitle;
                titleTime = setTimeout(function() {
                    document.title = originTitle;
                }, 2000);
            }
        })
    </script>

<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js">
</script>
  </div>
</body>
</html>